<template>
    <div>
        <el-button type="primary" size="default" @click="handleDel"
            :style="{ marginBottom: '.1563rem', marginTop: '.1042rem' }" v-if="SelArr.length > 0">批量删除</el-button>
        <el-table :data="tableData" :default-checked-keys="defaultCheckedKeys" stripe ref="multipleTableRef" style=""
            :header-cell-style="{
                'height': '.4167rem',
                'background': '#3F7233',
                'color': '#FFFFFF',
                'font-size': '.0833rem',
                'padding-left': '.2292rem'
            }" :cell-style="{ 'text-align': 'center' }" empty-text="请添加商品" @select-all="selectAll"
            @select="handleSelectionChange">
            <!-- @selection-change="handleSelectionChange" -->
            <el-table-column type="selection" width="100">
            </el-table-column>
            <el-table-column label="图片" width="120">
                <template #default="scope">
                    <el-image style="width: .5208rem; height: .5208rem; border-radius: .0313rem;"
                        :src="scope.row.goods.image" :crossorigin="null" />
                </template>
            </el-table-column>
            <el-table-column label="商品名称" width="140">
                <template #default="scope">
                    <div class="goods-name">
                        {{ scope.row.goods.name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="产品编号" width="140">
                <template #default="scope">
                    <div class="goods-sn">
                        {{ scope.row.goods.sn }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="总数量" width="140">
                <template #default="scope">
                    <div class="goods-num">
                        <!-- {{ scope.row.goods_num }} -->
                        <el-input-number v-model="scope.row.goods_num" :min="1" @change="handleChange(scope.row)"
                            class="custom-input" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="A面" width="140">
                <template #default="scope">
                    <div class="goods-num">
                        <!-- {{ scope.row.goods_num }} -->
                        <el-input-number v-model="scope.row.value_1" :min="0" @change="setFace(scope.row, 1)"
                            class="custom-input" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="B面" width="140">
                <template #default="scope">
                    <div class="goods-num">
                        <!-- {{ scope.row.goods_num }} -->
                        <el-input-number v-model="scope.row.value_2" :min="0" @change="setFace(scope.row, 2)"
                            class="custom-input" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="C面" width="140">
                <template #default="scope">
                    <div class="goods-num">
                        <!-- {{ scope.row.goods_num }} -->
                        <el-input-number v-model="scope.row.value_3" :min="0" @change="setFace(scope.row, 3)"
                            class="custom-input" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="D面" width="150">
                <template #default="scope">
                    <div class="goods-num">
                        <!-- {{ scope.row.goods_num }} -->
                        <el-input-number v-model="scope.row.value_4" :min="0" @change="setFace(scope.row, 4)"
                            class="custom-input" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="售价" width="180">
                <template #default="scope">
                    <div class="goods-price">
                        ￥{{ scope.row.goods.goods_price }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="danger" plain @click.prevent="deleteRow(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="my-paging">
            <MyPaging v-model="page" :total="total" :pagesize="10" v-if="tableData.length > 0" />
            <div class="btn" @click="handleCart" v-if="orderShow == 1">生成订单</div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch,watchEffect } from 'vue';
import { UserCart, CartFace } from '../../../api/user'
import { useUser } from '../../../store/user';
import { useRouter } from 'vue-router';
import { CartDel, CartUpdate, getAuth, CartSubmit, CartAll, CartSel } from '../../../api/goods'
import { ElMessage } from 'element-plus'
const router = useRouter()
const user = useUser()
const props = defineProps(['lists', "type"])
let { token } = user.userinfo

const multipleTableRef = ref()

// 页码
const page = ref(1)
const total = ref(0)
// 表格数据
const tableData = ref([])

let defaultCheckedKeys = ref([])

watchEffect(()=>{
    props.lists.forEach((item,index) => {
        if (item.selected == 1) {

            console.log("选择");
            defaultCheckedKeys.value.push(item.id)
            setTimeout(() => {
                multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
            }, 0);
        }
    })

})



if (props.lists.length > 0) {
    tableData.value = [...props.lists]

    defaultCheckedKeys.value = []
    props.lists.forEach((item,index) => {
        if (item.selected == 1) {

            console.log("选择");
            defaultCheckedKeys.value.push(item.id)
            setTimeout(() => {
                multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
            }, 0);
        }
    })


}


// 点击所有
const selectAll = (e) => {
    if (e.length > 0) {
        CartAll(props.type -1, 1, 0,token)


    } else {
        CartAll(props.type-1, 0, 0,token)
    }
}


let orderShow = ref(0)
getAuth(token).then(res => {

    console.log(res.data, "-asdlkjjdlk;");
    orderShow.value = res.data.data.goodsinfo_create_order
})

watch(() => props.lists, async (n) => {
    if (n.length > 0) {
        tableData.value = [...n]


        defaultCheckedKeys.value = []
        tableData.value.forEach(item => {

            if (item.selected == 1) {
                defaultCheckedKeys.value.push(item.id)
            }
        })


    }
})
if (user.userinfo) {
    let { token } = user.userinfo
    let res = await UserCart(page.value, token, props.type)
    let { count, lists } = res.data.data
    total.value = count
    tableData.value = lists



    defaultCheckedKeys.value = []
    tableData.value.forEach((item, index) => {
        if (item.selected == 1) {
            defaultCheckedKeys.value.push(item.id)
            setTimeout(() => {
                multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
            }, 0);
        }
    })

    console.log(defaultCheckedKeys.value);

    watch(page, async (n) => {
        let res = await UserCart(n, token, props.type)
        let { count, lists } = res.data.data
        total.value = count
        tableData.value = lists
        console.log('page');

        // lists.forEach((item,index) => {

        //     if(item.selected == 1){
        //         console.log(item.selected,index,"oih");
        //         multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
        //     }

        // })

        defaultCheckedKeys.value = []
        tableData.value.forEach((item, index) => {
            if (item.selected == 1) {
                console.log("aihosa");
                defaultCheckedKeys.value.push(item.id)
                multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
            }
        })
    })
    watch(() => user.cart, async () => {
        let res = await UserCart(page.value, token, props.type)
        let { count, lists } = res.data.data
        total.value = count
        tableData.value = lists

        console.log("car");

        defaultCheckedKeys.value = []
        tableData.value.forEach((item, index) => {
            if (item.selected == 1) {
                defaultCheckedKeys.value.push(item.id)
                multipleTableRef.value.toggleRowSelection(tableData.value[index], true)
            }
        })
    })

}
const handleCart = () => {
    // router.push('/cart')

    // 添加订单
    let arr = 0
    tableData.value.forEach((item, index) => {
        if (item.selected == 1) {
            arr += 1
        }
    })

    console.log(arr);

    if (arr == 0){
        ElMessage.error('请选择商品')
        return
    }
    CartSubmit({ type: props.type }, token).then(res => {
        router.push({
            path: '/cart',
            query: {
                type: props.type
            }
        })

    })


}
// 修改面
const setFace = (row, index) => {
    let a = 'value_' + index
    let { id, goods_num } = row
    CartFace(id, row[a], index, token).then(res => {
        ElMessage.success(res.data.msg)
    })
}
// 删除按钮
const deleteRow = (index, row) => {
    tableData.value.splice(index, 1)
    let { id } = row
    CartDel(id, token).then(res => {
        ElMessage.success(res.data.msg)
    })
}

const handleChange = async (row) => {
    let { id, goods_num } = row
    let { token } = user.userinfo
    let res = await CartUpdate(id, goods_num, token)
}
const SelArr = ref([])
const handleSelectionChange = (selection, row) => {

    console.log(selection, row);
    if (row.selected == 0) {
        CartSel(props.type-1, 1, row.id, 1,token).then(res => {
        })


    } else {
        CartSel(props.type-1, 0, row.id, 1,token).then(res => {
        })
    }

    tableData.value.forEach((item, index) => {
        if (item.id == row.id) {

            console.log("======", tableData.value[index].selected);
            // SelArr.value.push(item)
            tableData.value[index].selected = tableData.value[index].selected == 1 ? 0 : 1
        }
    })

}


const handleDel = () => {
    let arr = []
    SelArr.value.forEach(item => {
        arr.push(item.id)
    })
    // console.log(arr);
    CartDel(arr, token).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.msg)
        }
        tableData.value = tableData.value.filter(item => !arr.includes(item.id))
    })
}
</script>

<style scoped lang="scss">
.my-paging {
    margin-top: .1563rem;
    display: flex;
    justify-content: center;
    align-items: center;

    .btn {
        margin-bottom: 0.2083rem;
        width: .4167rem;
        height: .1563rem;
        background-color: #3f7233;
        cursor: pointer;
        color: white;
        text-align: center;
        line-height: .1563rem;

        &:hover {
            opacity: 0.8;
        }

        &:active {
            opacity: 1;
        }
    }
}

.goods-name,
.goods-sn {
    font-size: .0833rem;
    font-weight: 400;
    color: #333333;
}

.goods-price {
    font-size: .0938rem;
    font-weight: 400;
    color: #E71A1A;
}

/* .goods-num {
    width: .4167rem;
    height: .2083rem;
    background: #EEEEEE;
    border-radius: .0208rem;
    text-align: center;
    line-height: .2083rem;
    font-size: .0833rem;
    font-weight: 400;
    color: #333333;
} */
.custom-input {
    max-width: .625rem;
}
</style>